PROJECT = "nfwq_weather_ssd1306_air640w"
VERSION = "1.0.0"

_G.sys = require("sys")
_G.mqtt2 = require("mqtt2")
--WiFi信息
_G.mine = require("my_demo")

if wlan ~= nil then
    log.info("mac", wlan.get_mac())
    local ssid = mine.wifi_ssid
    local password = mine.wifi_passwd
    wlan.connect(ssid, password)
end

function first_pages(weather)
    disp.clear() -- 清屏
    if wlan.ready() then
        socket.ntpSync()
    end
    disp.drawStr(os.date("%Y-%m-%d %H:%M:%S"), 1, 12) -- 写日期
    disp.drawStr("城市: " .. weather.city .. " ...", 1, 24)
    disp.drawStr("温度: " .. weather.temperature .. " *C", 24, 36)
    disp.drawStr("湿度: " .. weather.humidity .. " RH", 24, 48)
    disp.drawStr("网络: " .. tostring(wlan.rssi()), 85, 60)
    disp.update()
end

function display_str(str)
    disp.clear() -- 清屏
    disp.drawStr(str, 1, 12)
    disp.drawStr("南风未起: ".."@luatOS".."& air640w", 1, 24)
    disp.drawStr("我的个人博客: ", 1, 36)
    disp.drawStr("yajs666.gitee.io", 29, 48)
    disp.drawStr("网络: " .. tostring(wlan.rssi()), 85, 60)
    disp.update()
end

-- 初始化显示屏
disp.init({mode = "i2c_sw", pin0 = 18, pin1 = 19})
disp.setFont(1)
display_str("启动中...")

sys.taskInit(
    function()
        --http://api.bilibili.com/x/relation/stat?vmid=581394370 B站粉丝数
        while 1 do
            if socket.isReady() then
                http.get(
                    "http://www.luatos.com/api/public/weather2?city=411325",
                    nil,
                    function(code, headers, body)
                        local data = {}
                        data = body
                        --"'" .. body .. "'"
                        log.info("天气", code, data)
                        mydata = data
                        --json.encode(data)
                        jsondata = json.decode(mydata)
                        log.info("天气", jsondata.live.humidity)
                        weather = {}
                        weather.city = jsondata.city
                        weather.temperature = jsondata.live.temperature
                        weather.humidity = jsondata.live.humidity
                        first_pages(weather)
                    end
                )
                sys.wait(5000)
            else
                sys.wait(2000)
            end
        end
    end
)
-- 用户代码已结束---------------------------------------------
-- 结尾总是这一句
sys.run()
